#include "stockinstatistics.h"
#include "inventoryservice.h"
#include "appinitializer.h"
#include <QFont>
#include <QDate>
#include <QMessageBox>
#include <QDebug>
#include <QHeaderView>
#include <QSpacerItem>
#include <QFileDialog>
#include <QTextStream>
#include <QApplication>
#include <QStackedWidget>

StockInStatistics::StockInStatistics(const QMap<QString, QVariant> &userInfo, QWidget *parent)
    : QWidget(parent), m_currentUser(userInfo)
{
    // 初始化服务层
    Database *db = AppInitializer::database();
    m_inventoryService = new InventoryService(db, this);

    initUI();
    setupStyles();
    setupTable();
    loadProducts();
    loadData();

    // 连接信号槽
    connect(m_btnReturn, &QPushButton::clicked, this, &StockInStatistics::onReturnClicked);
    connect(m_btnRefresh, &QPushButton::clicked, this, &StockInStatistics::onRefreshClicked);
    connect(m_btnExport, &QPushButton::clicked, this, &StockInStatistics::onExportClicked);
    connect(m_btnSearch, &QPushButton::clicked, this, &StockInStatistics::onSearchClicked);
    connect(m_btnReset, &QPushButton::clicked, this, &StockInStatistics::onResetClicked);
    connect(m_cmbProduct, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &StockInStatistics::onProductChanged);
}

StockInStatistics::~StockInStatistics()
{
}

void StockInStatistics::initUI()
{
    // 创建主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(8, 8, 8, 8);
    m_mainLayout->setSpacing(8);

    // 移除标题标签以扩大内容展示区域

    // 创建顶部按钮和统计信息布局
    m_topButtonLayout = new QHBoxLayout();
    m_topButtonLayout->setSpacing(15);

    m_btnReturn = new QPushButton(tr("返回"), this);
    m_btnReturn->setObjectName("returnButton");
    m_btnReturn->setFixedSize(100, 40);

    // 创建统计信息标签（紧凑型）
    m_lblTotalRecords = new QLabel(tr("总记录数: 0"), this);
    m_lblTotalRecords->setObjectName("compactStatistics");
    
    m_lblTotalQuantity = new QLabel(tr("总入库数量: 0"), this);
    m_lblTotalQuantity->setObjectName("compactStatistics");
    
    m_lblTotalAmount = new QLabel(tr("总入库金额: ¥0.00"), this);
    m_lblTotalAmount->setObjectName("compactStatistics");
    
    m_lblAveragePrice = new QLabel(tr("平均单价: ¥0.00"), this);
    m_lblAveragePrice->setObjectName("compactStatistics");

    m_btnRefresh = new QPushButton(tr("刷新"), this);
    m_btnRefresh->setObjectName("refreshButton");
    m_btnRefresh->setFixedSize(100, 40);

    m_btnExport = new QPushButton(tr("导出"), this);
    m_btnExport->setObjectName("exportButton");
    m_btnExport->setFixedSize(100, 40);

    m_topButtonLayout->addWidget(m_btnReturn);
    m_topButtonLayout->addWidget(m_lblTotalRecords);
    m_topButtonLayout->addWidget(m_lblTotalQuantity);
    m_topButtonLayout->addWidget(m_lblTotalAmount);
    m_topButtonLayout->addWidget(m_lblAveragePrice);
    m_topButtonLayout->addStretch();
    m_topButtonLayout->addWidget(m_btnRefresh);
    m_topButtonLayout->addWidget(m_btnExport);

    m_mainLayout->addLayout(m_topButtonLayout, 0);

    // 创建滚动区域
    m_scrollArea = new QScrollArea(this);
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    m_contentWidget = new QWidget();
    m_contentLayout = new QVBoxLayout(m_contentWidget);
    m_contentLayout->setContentsMargins(5, 5, 5, 5);
    m_contentLayout->setSpacing(10);

    // 创建筛选区域
    m_filterGroup = new QGroupBox(tr("筛选条件"), m_contentWidget);
    m_filterGridLayout = new QGridLayout(m_filterGroup);
    m_filterGridLayout->setSpacing(15);
    m_filterGridLayout->setContentsMargins(20, 20, 20, 20);

    // 筛选控件
    m_lblStartDate = new QLabel(tr("开始日期:"), m_filterGroup);
    m_dateStart = new QDateEdit(QDate::currentDate().addDays(-30), m_filterGroup);
    m_dateStart->setCalendarPopup(true);
    m_dateStart->setDisplayFormat("yyyy-MM-dd");

    m_lblEndDate = new QLabel(tr("结束日期:"), m_filterGroup);
    m_dateEnd = new QDateEdit(QDate::currentDate(), m_filterGroup);
    m_dateEnd->setCalendarPopup(true);
    m_dateEnd->setDisplayFormat("yyyy-MM-dd");

    m_lblProduct = new QLabel(tr("商品:"), m_filterGroup);
    m_cmbProduct = new QComboBox(m_filterGroup);
    m_cmbProduct->setMinimumWidth(200);

    m_lblSupplier = new QLabel(tr("供应商:"), m_filterGroup);
    m_edtSupplier = new QLineEdit(m_filterGroup);
    m_edtSupplier->setPlaceholderText(tr("输入供应商名称"));

    m_btnSearch = new QPushButton(tr("查询"), m_filterGroup);
    m_btnSearch->setObjectName("searchButton");
    m_btnSearch->setFixedSize(80, 35);

    m_btnReset = new QPushButton(tr("重置"), m_filterGroup);
    m_btnReset->setObjectName("resetButton");
    m_btnReset->setFixedSize(80, 35);

    // 布局筛选控件
    m_filterGridLayout->addWidget(m_lblStartDate, 0, 0);
    m_filterGridLayout->addWidget(m_dateStart, 0, 1);
    m_filterGridLayout->addWidget(m_lblEndDate, 0, 2);
    m_filterGridLayout->addWidget(m_dateEnd, 0, 3);
    m_filterGridLayout->addWidget(m_btnSearch, 0, 4);
    m_filterGridLayout->addWidget(m_lblProduct, 1, 0);
    m_filterGridLayout->addWidget(m_cmbProduct, 1, 1);
    m_filterGridLayout->addWidget(m_lblSupplier, 1, 2);
    m_filterGridLayout->addWidget(m_edtSupplier, 1, 3);
    m_filterGridLayout->addWidget(m_btnReset, 1, 4);

    m_contentLayout->addWidget(m_filterGroup);

    // 创建数据表格
    m_tableWidget = new QTableWidget(m_contentWidget);
    m_contentLayout->addWidget(m_tableWidget, 1);

    m_scrollArea->setWidget(m_contentWidget);
    m_mainLayout->addWidget(m_scrollArea, 1);
}

void StockInStatistics::setupStyles()
{
    // 设置整体样式
    this->setStyleSheet(
        "QWidget {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #f8f9fa, stop:1 #e9ecef);"
        "    font-family: 'Microsoft YaHei', Arial, sans-serif;"
        "}"
        
        "QPushButton {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #3498db, stop:1 #2980b9);"
        "    color: white;"
        "    border: none;"
        "    border-radius: 8px;"
        "    font-size: 14px;"
        "    font-weight: bold;"
        "    padding: 10px 20px;"
        "    min-height: 35px;"
        "}"
        
        "QPushButton:hover {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #5dade2, stop:1 #3498db);"
        "    border: 2px solid #2980b9;"
        "}"
        
        "QPushButton:pressed {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #2980b9, stop:1 #21618c);"
        "}"
        
        "#returnButton {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #e74c3c, stop:1 #c0392b);"
        "}"
        
        "#returnButton:hover {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #ec7063, stop:1 #e74c3c);"
        "}"
        
        "#searchButton, #refreshButton {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #27ae60, stop:1 #229954);"
        "}"
        
        "#searchButton:hover, #refreshButton:hover {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #58d68d, stop:1 #27ae60);"
        "}"
        
        "#resetButton {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #f39c12, stop:1 #e67e22);"
        "}"
        
        "#resetButton:hover {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #f7dc6f, stop:1 #f39c12);"
        "}"
        
        "QGroupBox {"
        "    font-size: 16px;"
        "    font-weight: bold;"
        "    color: #2c3e50;"
        "    border: 2px solid #e8eaed;"
        "    border-radius: 12px;"
        "    margin-top: 15px;"
        "    background-color: white;"
        "    border: 1px solid #e8eaed;"
        "    padding-top: 10px;"
        "}"
        
        "QGroupBox::title {"
        "    subcontrol-origin: margin;"
        "    left: 15px;"
        "    padding: 5px 12px;"
        "    background: qlineargradient(x1:0, y1:0, x2:1, y2:0, "
        "                stop:0 #3498db, stop:1 #2980b9);"
        "    color: white;"
        "    border-radius: 6px;"
        "    font-size: 14px;"
        "    font-weight: bold;"
        "}"
        
        "QLabel {"
        "    font-size: 14px;"
        "    color: #2c3e50;"
        "    font-weight: normal;"
        "}"
        
        "#compactStatistics {"
        "    font-size: 12px;"
        "    color: #34495e;"
        "    font-weight: bold;"
        "    background-color: rgba(255, 255, 255, 0.8);"
        "    border: 1px solid #bdc3c7;"
        "    border-radius: 4px;"
        "    padding: 4px 8px;"
        "    margin: 2px;"
        "    min-width: 120px;"
        "}"
        
        "#statisticsValue {"
        "    font-size: 18px;"
        "    font-weight: bold;"
        "    color: #27ae60;"
        "    background: qlineargradient(x1:0, y1:0, x2:1, y2:0, "
        "                stop:0 #e8f5e8, stop:1 #f0f8f0);"
        "    padding: 8px 12px;"
        "    border-radius: 6px;"
        "    border: 1px solid #a9dfbf;"
        "}"
        
        "QLineEdit, QComboBox, QDateEdit {"
        "    padding: 10px 15px;"
        "    border: 2px solid #e8eaed;"
        "    border-radius: 8px;"
        "    font-size: 14px;"
        "    background-color: white;"
        "    min-height: 25px;"
        "}"
        
        "QLineEdit:focus, QComboBox:focus, QDateEdit:focus {"
        "    border-color: #3498db;"
        "    outline: none;"
        "    border: 3px solid #3498db;"
        "    background-color: #fbfcfd;"
        "}"
        
        "QComboBox::drop-down {"
        "    border: none;"
        "    width: 20px;"
        "}"
        
        "QComboBox::down-arrow {"
        "    image: none;"
        "    border-left: 5px solid transparent;"
        "    border-right: 5px solid transparent;"
        "    border-top: 5px solid #7f8c8d;"
        "    margin-right: 5px;"
        "}"
        
        "QScrollArea {"
        "    border: none;"
        "    background-color: transparent;"
        "}"
    );
}

void StockInStatistics::setupTable()
{
    // 设置表格列
    QStringList headers;
    headers << tr("入库单号") << tr("商品名称") << tr("分类") << tr("入库数量") 
            << tr("入库单价") << tr("入库金额") << tr("入库时间") 
            << tr("操作员") << tr("供应商") << tr("备注");
    
    m_tableWidget->setColumnCount(headers.size());
    m_tableWidget->setHorizontalHeaderLabels(headers);
    
    // 设置表格样式
    m_tableWidget->setStyleSheet(
        "QTableWidget {"
        "    gridline-color: #e8eaed;"
        "    background-color: white;"
        "    alternate-background-color: #f8f9fa;"
        "    selection-background-color: #3498db;"
        "    selection-color: white;"
        "    border: 2px solid #e8eaed;"
        "    border-radius: 10px;"
        "    font-size: 13px;"
        "    border: 1px solid #e8eaed;"
        "}"
        
        "QTableWidget::item {"
        "    padding: 12px 8px;"
        "    border-bottom: 1px solid #e8eaed;"
        "}"
        
        "QTableWidget::item:selected {"
        "    background-color: #3498db;"
        "    color: white;"
        "}"
        
        "QHeaderView::section {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #34495e, stop:1 #2c3e50);"
        "    color: white;"
        "    padding: 10px;"
        "    border: none;"
        "    font-weight: bold;"
        "    font-size: 14px;"
        "}"
        
        "QHeaderView::section:hover {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 #5d6d7e, stop:1 #34495e);"
        "}"
    );
    
    // 设置表格属性
    m_tableWidget->setAlternatingRowColors(true);
    m_tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    m_tableWidget->setSortingEnabled(true);
    m_tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    
    // 设置列宽
    QHeaderView *header = m_tableWidget->horizontalHeader();
    header->setStretchLastSection(true);
    header->resizeSection(0, 100);  // 入库单号
    header->resizeSection(1, 150);  // 商品名称
    header->resizeSection(2, 100);  // 分类
    header->resizeSection(3, 100);  // 入库数量
    header->resizeSection(4, 100);  // 入库单价
    header->resizeSection(5, 100);  // 入库金额
    header->resizeSection(6, 150);  // 入库时间
    header->resizeSection(7, 100);  // 操作员
    header->resizeSection(8, 120);  // 供应商
    
    // 设置行高
    m_tableWidget->verticalHeader()->setDefaultSectionSize(40);
    m_tableWidget->verticalHeader()->setVisible(false);
}

void StockInStatistics::loadData()
{
    try {
        m_allRecords = m_inventoryService->getAllStockInRecords();
        m_filteredRecords = m_allRecords;
        
        // 更新表格显示
        updateTable();
        updateStatistics();
        
        qDebug() << "Loaded" << m_allRecords.size() << "stock in records";
    } catch (const std::exception &e) {
        QMessageBox::warning(this, tr("错误"), tr("加载数据失败: %1").arg(e.what()));
    }
}

void StockInStatistics::loadProducts()
{
    try {
        m_cmbProduct->clear();
        m_cmbProduct->addItem(tr("全部商品"), -1);
        
        // 获取所有分类
        auto categories = m_inventoryService->getAllCategories();
        for (const auto &category : categories) {
            int categoryId = category["category_id"].toInt();
            
            // 获取该分类下的商品
            auto products = m_inventoryService->getProductsByCategory(categoryId);
            for (const auto &product : products) {
                QString productName = product["product_name"].toString();
                int productId = product["product_id"].toInt();
                m_cmbProduct->addItem(productName, productId);
            }
        }
    } catch (const std::exception &e) {
        QMessageBox::warning(this, tr("错误"), tr("加载商品列表失败: %1").arg(e.what()));
    }
}

void StockInStatistics::filterData()
{
    QString startDate = m_dateStart->date().toString("yyyy-MM-dd 00:00:00");
    QString endDate = m_dateEnd->date().toString("yyyy-MM-dd 23:59:59");
    int productId = m_cmbProduct->currentData().toInt();
    QString supplier = m_edtSupplier->text().trimmed();
    
    try {
        if (productId == -1) productId = 0;  // 转换为DAO层期望的值
        
        m_filteredRecords = m_inventoryService->getStockInRecordsByCondition(
            startDate, endDate, productId, supplier);
        
        updateTable();
        updateStatistics();
        
        qDebug() << "Filtered to" << m_filteredRecords.size() << "records";
    } catch (const std::exception &e) {
        QMessageBox::warning(this, tr("错误"), tr("筛选数据失败: %1").arg(e.what()));
    }
}

void StockInStatistics::updateTable()
{
    m_tableWidget->setRowCount(m_filteredRecords.size());
    
    for (int row = 0; row < m_filteredRecords.size(); ++row) {
        const auto &record = m_filteredRecords[row];
        
        // 入库单号
        m_tableWidget->setItem(row, 0, new QTableWidgetItem(
            record["in_id"].toString()));
        
        // 商品名称
        m_tableWidget->setItem(row, 1, new QTableWidgetItem(
            record["product_name"].toString()));
        
        // 分类
        m_tableWidget->setItem(row, 2, new QTableWidgetItem(
            record["category_name"].toString()));
        
        // 入库数量
        m_tableWidget->setItem(row, 3, new QTableWidgetItem(
            record["in_quantity"].toString()));
        
        // 入库单价
        double price = record["in_price"].toDouble();
        m_tableWidget->setItem(row, 4, new QTableWidgetItem(
            QString("¥%1").arg(price, 0, 'f', 2)));
        
        // 入库金额
        int quantity = record["in_quantity"].toInt();
        double amount = price * quantity;
        m_tableWidget->setItem(row, 5, new QTableWidgetItem(
            QString("¥%1").arg(amount, 0, 'f', 2)));
        
        // 入库时间
        QString timeStr = record["in_time"].toDateTime().toString("yyyy-MM-dd hh:mm:ss");
        m_tableWidget->setItem(row, 6, new QTableWidgetItem(timeStr));
        
        // 操作员
        m_tableWidget->setItem(row, 7, new QTableWidgetItem(
            record["operator_name"].toString()));
        
        // 供应商
        m_tableWidget->setItem(row, 8, new QTableWidgetItem(
            record["supplier"].toString()));
        
        // 备注
        m_tableWidget->setItem(row, 9, new QTableWidgetItem(
            record["note"].toString()));
    }
}

void StockInStatistics::updateStatistics()
{
    int totalRecords = m_filteredRecords.size();
    int totalQuantity = 0;
    double totalAmount = 0.0;
    
    for (const auto &record : m_filteredRecords) {
        int quantity = record["in_quantity"].toInt();
        double price = record["in_price"].toDouble();
        
        totalQuantity += quantity;
        totalAmount += quantity * price;
    }
    
    double averagePrice = totalQuantity > 0 ? totalAmount / totalQuantity : 0.0;
    
    m_lblTotalRecords->setText(tr("总记录数: %1").arg(totalRecords));
    m_lblTotalQuantity->setText(tr("总入库数量: %1").arg(totalQuantity));
    m_lblTotalAmount->setText(tr("总入库金额: ¥%1").arg(totalAmount, 0, 'f', 2));
    m_lblAveragePrice->setText(tr("平均单价: ¥%1").arg(averagePrice, 0, 'f', 2));
}

void StockInStatistics::clearFilters()
{
    m_dateStart->setDate(QDate::currentDate().addDays(-30));
    m_dateEnd->setDate(QDate::currentDate());
    m_cmbProduct->setCurrentIndex(0);
    m_edtSupplier->clear();
}

// 槽函数实现
void StockInStatistics::onReturnClicked()
{
    // 获取父级IM窗口并切换回入库页面
    QWidget *parent = this->parentWidget();
    while (parent && !qobject_cast<QStackedWidget*>(parent)) {
        parent = parent->parentWidget();
    }
    
    if (QStackedWidget *stackedWidget = qobject_cast<QStackedWidget*>(parent)) {
        // 切换回入库页面（索引0，第一个页面）
        stackedWidget->setCurrentIndex(0);
    }
}

void StockInStatistics::onRefreshClicked()
{
    loadData();
    QMessageBox::information(this, tr("提示"), tr("数据已刷新"));
}

void StockInStatistics::onSearchClicked()
{
    filterData();
}

void StockInStatistics::onResetClicked()
{
    clearFilters();
    m_filteredRecords = m_allRecords;
    updateTable();
    updateStatistics();
}

void StockInStatistics::onExportClicked()
{
    QString fileName = QFileDialog::getSaveFileName(
        this, tr("导出入库统计"), 
        QString("入库统计_%1.csv").arg(QDate::currentDate().toString("yyyyMMdd")),
        tr("CSV文件 (*.csv)"));
    
    if (fileName.isEmpty()) {
        return;
    }
    
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, tr("错误"), tr("无法创建文件"));
        return;
    }
    
    QTextStream out(&file);
    out.setCodec("UTF-8");
    
    // 写入表头
    out << "入库单号,商品名称,分类,入库数量,入库单价,入库金额,入库时间,操作员,供应商,备注\n";
    
    // 写入数据
    for (const auto &record : m_filteredRecords) {
        double price = record["in_price"].toDouble();
        int quantity = record["in_quantity"].toInt();
        double amount = price * quantity;
        QString timeStr = record["in_time"].toDateTime().toString("yyyy-MM-dd hh:mm:ss");
        
        out << record["in_id"].toString() << ","
            << record["product_name"].toString() << ","
            << record["category_name"].toString() << ","
            << quantity << ","
            << price << ","
            << amount << ","
            << timeStr << ","
            << record["operator_name"].toString() << ","
            << record["supplier"].toString() << ","
            << record["note"].toString() << "\n";
    }
    
    file.close();
    QMessageBox::information(this, tr("成功"), tr("数据已导出到: %1").arg(fileName));
}

void StockInStatistics::onProductChanged(int index)
{
    Q_UNUSED(index)
    // 商品选择改变时可以添加额外逻辑
}